#include "opencv.h"
#include "handModel.h"
#include "selfAdaptionSkin.h"

/*
double t = (double)getTickCount();
t = (double)getTickCount() - t;
printf("tdetection time = %gms\n", t*1000./cv::getTickFrequency());
*/
int main(int argc, char** argv)
{
	int i,j;
	VideoCapture cap(0);
	string configFile = "modelParameter//config.txt";
	string contrlPointsFile = "modelParameter//conP.txt";
	string knotsCountFile = "modelParameter//knotsCount.txt";
	string pivotsFile = "modelParameter//pivP.txt";
	string tipsFile = "modelParameter//tipP.txt";
	string partitionPointsIdxFile = "modelParameter//partitionPointsIdx.txt";
	string measurementPoints = "modelParameter//meaP.txt";



	handModel hand(configFile, contrlPointsFile, knotsCountFile,
		pivotsFile, tipsFile, partitionPointsIdxFile, measurementPoints);


	selfAdaptionSkin skinDetector;

	float* stateD = new float[14];
	stateD[0] = 300;
	stateD[1] = 300;
	stateD[2] = 0;
	stateD[3] = 0.7;
	stateD[4] = 0;
	stateD[5] = 1;
	stateD[6] = 0;
	stateD[7] = 1;
	stateD[8] = 0;
	stateD[9] = 1;
	stateD[10] = 0;
	stateD[11] = 1;
	stateD[12] = 0;
	stateD[13] = 0;
	int counter = 0;
	Mat mask;
	mask = Mat::zeros(480, 640, CV_8UC1);
	hand.updateState(stateD);
	float confidence;
	float fitness = 0;
	while(1)
	{
		double t = (double)getTickCount();
		
		Mat source;
		Mat gray;
		Mat showImg;
		

		gray = Mat::zeros(480, 640, CV_8UC1);

		cap>>source;

		showImg = source.clone();

		
		hand.show(showImg, CV_RGB(255, 0, 0), 2);


		drawContours(mask, hand.DTContours, -1, CV_RGB(255, 255, 255) ,-1);
		drawContours(mask, hand.SBContours, -1, CV_RGB(255, 255, 255) ,-1);


//		skinDetector.getBestParament(source, mask);


		
		
		skinDetector.skinDetectLC(source, gray);
		

		confidence = hand.contourConfidence(hand.measurementPoints, &gray, &gray, 0);

		

/*

		cout<<fitness<<endl;
		cout<<confidence<<endl;
*/
		//arfwjkerg
		if (fitness < confidence)
//		if(1)
		{
			fitness = confidence;
			skinDetector.getBestParamentMask(source, mask);
			
		}

		cout<<fitness<<endl;
		medianBlur(gray,gray,7);
		

		imshow("sun",showImg);
		imshow("xiao", gray);
		imshow("mask", mask);


		if (waitKey(1) > 0)
		{
			break;
		}

		t = (double)getTickCount() - t;
		printf("tdetection time = %gms\n", t*1000./cv::getTickFrequency());

	}

	return 0;
}